package yiran.itemuse.data;

import org.bukkit.inventory.ItemStack;
import yiran.itemuse.output.Logger;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Map;

public class ItemCommandService {

    public void bindCommandToItem(ItemStack item, String command, boolean consume) {
        String itemKey = generateUniqueItemKey(item);
        String sql = "INSERT OR REPLACE INTO item_commands (item_key, command, consume) VALUES (?, ?, ?)";

        try (Connection conn = DatabaseService.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {

            stmt.setString(1, itemKey);
            stmt.setString(2, command);
            stmt.setBoolean(3, consume);
            stmt.executeUpdate();

        } catch (SQLException e) {
            Logger.error("保存物品指令失败: " + e.getMessage());
        }
    }

    public void removeCommandFromItem(ItemStack item) {
        String itemKey = generateUniqueItemKey(item);
        String sql = "DELETE FROM item_commands WHERE item_key = ?";

        try (Connection conn = DatabaseService.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {

            stmt.setString(1, itemKey);
            stmt.executeUpdate();

        } catch (SQLException e) {
            Logger.error("删除物品指令失败: " + e.getMessage());
        }
    }

    public CommandData getCommandDataByItem(ItemStack item) {
        if (item == null) return null;

        String itemKey = generateUniqueItemKey(item);
        String sql = "SELECT command, consume FROM item_commands WHERE item_key = ?";

        try (Connection conn = DatabaseService.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {

            stmt.setString(1, itemKey);
            ResultSet rs = stmt.executeQuery();

            if (rs.next()) {
                return new CommandData(
                        rs.getString("command"),
                        rs.getBoolean("consume")
                );
            }
        } catch (SQLException e) {
            Logger.error("获取物品指令失败: " + e.getMessage());
        }
        return null;
    }


    private String generateUniqueItemKey(ItemStack item) {
        // 使用Bukkit序列化API
        Map<String, Object> serialized = item.serialize();
        // 移除动态变化的字段
        serialized.remove("amount");
        // 生成稳定哈希
        return Integer.toHexString(serialized.toString().hashCode());
    }

    public static class CommandData {
        private final String command;
        private final boolean consume;

        public CommandData(String command, boolean consume) {
            this.command = command;
            this.consume = consume;
        }

        public String getCommand() {
            return command;
        }

        public boolean shouldConsume() {
            return consume;
        }
    }
}

